<template>
	<view class="schedule_add_or_edit">
		<g-watermark/>
		<u-form :model="formData" ref="form" label-width="180">
			<u-form-item label="标题" prop="title" required>
				<u-input v-model="formData.title" placeholder="请输入标题" />
			</u-form-item>
			<u-form-item label="开始时间" prop="myDate" required>
				<view style="display: flex;justify-content: space-between;width: 100%;">
					<view class="" style="width: 100%;">
						<u-input disabled v-model="formData.myDate" placeholder="请选择开始时间" />
						<u-input disabled v-model="formData.endDate" placeholder="请选择结束时间" />
					</view>
					<u-icon name="arrow-down" @click="showTime=true"></u-icon>
				</view>
			</u-form-item>
			<u-form-item label="是否完成" prop="closed" v-if="isUpdate!=0">
				<u-switch v-model="formData.closed"></u-switch>
			</u-form-item>
			<u-form-item label="是否共享" prop="shared">
				<u-switch v-model="formData.shared"></u-switch>
			</u-form-item>
			<u-form-item label="是否提醒" prop="remind" v-if="isUpdate!=2">
				<u-switch v-model="formData.remind"></u-switch>
			</u-form-item>
			<u-form-item label="提醒时间" prop="beforeName" required v-if="formData.remind">
				<view style="display: flex;justify-content: space-between;width: 100%;">
					<u-input disabled v-model="formData.beforeName" placeholder="请选择提醒时间" />
					<u-icon name="arrow-down" @click="showBefore=true"></u-icon>
				</view>
			</u-form-item>
			<u-form-item label="将日程分配给" prop="mine" required v-if="isUpdate!=2">
				<view style="width: 100%;">
					<view>
						<u-checkbox v-model="formData.mine" name="1" @change="() => $forceUpdate()">自己</u-checkbox>
						<u-checkbox v-model="formData.others" name="1"
							:disabled="isUpdate==1 && formData.others && !isMultiDeptistUserRealNames">他人</u-checkbox>
						<u-button size="mini" @click="handleSelectUser" v-if="formData.others">选择</u-button>
					</view>
					<view v-if="formData.others"
						style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
						<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers']"
							:key="item.key" @close="handleCloseTag(index)" closeable />
					</view>
				</view>
			</u-form-item>
			<u-form-item label="内容" prop="content" required>
				<u-input type="textarea" :height="150" v-model="formData.content" placeholder="请输入内容" />
			</u-form-item>
			<u-form-item label="创建者" v-if="isUpdate!=0">
				<view>
					{{formData.distributer ||''}}
				</view>
			</u-form-item>
			<u-form-item label="附件">
				<FileUpload ref="fileUploadRef" :isUpdate='isUpdate' type="plan" />
			</u-form-item>
		</u-form>
		<view style="margin: 10upx 0;">
			注: 日程修改时，如果是分配给他人的，不联动修改
		</view>
		<u-button @click="submit" type="primary" v-if="isUpdate!=2">保存</u-button>
		<u-picker v-model="showBefore" mode="selector" :range="beforeList" range-key="label"
			@confirm="handleConfirmBefore"></u-picker>
		<MxDatepicker format="yyyy-mm-dd hh:ii:ss" type="rangetime" :show="showTime" :value="times" :show-tips="true"
			:begin-text="'开始时间'" :end-text="'结束时间'" :show-seconds="true" @confirm="handleConfirmTime"
			@cancel="showTime=false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
	</view>
</template>

<script>
	import {
		postFormAction
	} from "@/utils/request.js";
	import MxDatepicker from '../component/mx-datepicker/mx-datepicker'
	import SelectUser from '@/components/selectUser/index.vue'
	import FileUpload from '../component/file-upload/file-upload.vue'
	export default {
		components: {
			MxDatepicker,
			SelectUser,
			FileUpload
		},
		data() {
			return {
				url: {
					getPlan: '/plan/getPlan',
					create: '/plan/create',
					update: '/plan/update',
				},
				// 表单数据
				formData: {
					title: '',
					hadUsers: []
				},
				rules: {
					title: [{
						required: true,
						message: '请输入标题',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					beforeName: [{
						required: true,
						message: '请选择提醒时间',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					myDate: [{
						required: true,
						message: '请选择时间范围',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					content: [{
						required: true,
						message: '请输入内容',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
				},
				isUpdate: 1, //1编辑 0新增 2是详情
				isMultiDeptistUserRealNames: false,
				mainModel: {},
				showTime: false,
				times: [],
				showBefore: false,
				beforeList: [{
						label: '十分钟',
						value: 10,
					},
					{
						label: '二十分钟',
						value: 20,
					},
					{
						label: '三十分钟',
						value: 30,
					},
					{
						label: '四十五分钟',
						value: 45,
					},
					{
						label: '一小时',
						value: 60,
					},
					{
						label: '二小时',
						value: 120,
					},
					{
						label: '三小时',
						value: 180,
					},
					{
						label: '四小时',
						value: 240,
					},
					{
						label: '五小时',
						value: 300,
					},
					{
						label: '六小时',
						value: 360,
					},
					{
						label: '十二小时',
						value: 720,
					},
				]
			}
		},
		onLoad(options) {
			console.log("options", options)
			this.mainModel = JSON.parse(options.record)
			this.isUpdate = options.isUpdate
			console.log("this.mainModel", this.mainModel)
			if (this.isUpdate == 1) {
				this.updateTitle('编辑')
				this.fetch()
			} else if (this.isUpdate == 0) {
				this.updateTitle('新增')
				this.formData.mine = true
			} else {
				this.updateTitle('详情')
				this.fetch()
			}
		},
		computed: {
			ishadSelect() {
				return this.formData.mine || this.formData.others
			},
			beforeName() {
				if (this.formData.before) {
					const label = this.beforeList.find(item => item.value == this.formData.before).label
					console.log("label", label)
					return label
				} else {
					return ''
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			fetch() {
				postFormAction(this.url.getPlan, {
					id: this.mainModel.id
				}).then((res) => {
					this.formData = res.data;
					this.setBeforeLabel()
					this.getPlanAttachmentListByPlanIdData()
					this.times = [this.formData.myDate, this.formData.endDate];

					this.formData.mine = this.formData.mine == 1 ? true : false;
					this.formData.others = this.formData.others ? true : false;
					this.formData.hadUsers = [];
					if (this.formData.distUsers) {
						this.isMultiDeptistUserRealNames = false;
						const realNames = this.formData['distUserRealNames'].split(',');
						const userNames = this.formData.distUsers.split(',');
						realNames.forEach((item, index) => {
							this.formData['hadUsers'].push({
								key: userNames[index],
								name: userNames[index],
								title: item,
								realName: item,
							});
						});
					} else {
						this.isMultiDeptistUserRealNames = true;
					}
				});
			},
			//获取附件
			async getPlanAttachmentListByPlanIdData() {
				const res = await postFormAction('/plan/attachment/listByPlanId', {
					planId: this.formData.id
				})
				console.log("getPlanAttachmentListByPlanIdData", res)
				const {
					data
				} = res
				if (data && data.length) {
					this.$refs.fileUploadRef.fileList = data
				}
			},
			//设置提醒时间的label
			setBeforeLabel() {
				this.formData.beforeName = ''
				if (this.formData.before) {
					this.formData.beforeName = this.beforeList.find(item => item.value == this.formData.before).label
				}
			},
			/**
			 * 复写 binddata 方法，如果只是为了校验，无复杂自定义操作，可忽略此方法
			 * @param {String} name 字段名称
			 * @param {String} value 表单域的值
			 */
			// binddata(name,value){
			// 通过 input 事件设置表单指定 name 的值
			//   this.$refs.form.setValue(name, value)
			// },
			//回调时间
			handleConfirmTime(e) {
				const {
					value
				} = e
				if (value && value.length) {
					this.times = value
					this.formData.myDate = value[0]
					this.formData.endDate = value[1]
				}
				this.showTime = false
			},
			//提醒时间回调
			handleConfirmBefore(e) {
				console.log("handleConfirmBefore", e)
				this.formData.before = this.beforeList.find((_, index) => index == e[0]).value
				this.setBeforeLabel()
			},
			//选择人员
			handleSelectUser() {
				this.$refs.selectUserRef.open({
					users: this.formData['hadUsers']
				})
			},
			//选择用户回调
			handleSelectUserConfirm({
				selectUserList,
				label,
				value
			}) {
				console.log("handleSelectUserConfirm", selectUserList)
				this.formData.distUserRealNames = label
				this.formData.distUsers = value
				if (Array.isArray(this.formData['hadUsers'])) {
					this.formData['hadUsers'] = this.formData['hadUsers'].concat(selectUserList)
				} else {
					this.formData['hadUsers'] = selectUserList
				}
				this.$forceUpdate()
			},

			//删除已选用户
			handleCloseTag(index) {
				this.formData['hadUsers'].splice(index, 1)
				this.$forceUpdate()
			},
			// 触发提交表单
			submit() {
				this.$refs.form.validate(async valid => {
					if (valid) {
						console.log('验证通过');
						try {
							if (!this.ishadSelect) {
								uni.showToast({
									title: '将日程分配给不能为空',
									icon: 'none',
									type: 'warning'
								});
								return;
							}
							let formDate = Object.assign({}, this.formData);
							formDate.shared = formDate.shared ? '1' : '0';
							formDate.isClosed = formDate.closed ? '1' : '0';
							formDate.mine = formDate.mine ? '1' : '0';
							formDate.others = formDate.others ? '1' : '0';

							formDate.distUsers = '';
							formDate.distUserRealNames = '';
							//保证最新的数据
							let distUserRealNames = []
							let distUsers = []
							if (formDate.hadUsers && formDate.hadUsers.length) {
								formDate.hadUsers.forEach(item => {
									distUserRealNames.push(item.title)
									distUsers.push(item.key)
								})
								formDate.distUsers = distUsers.join(',')
								formDate.distUserRealNames = distUserRealNames.join(',')
							}
							const fileList = this.$refs.fileUploadRef.fileList
							console.log('fileList', fileList);
							if (fileList && fileList.length) {
								formDate.attachments = fileList.map(item => item.id).join(',')
							}
							delete formDate.hadUsers;
							console.log('formDate', formDate);
							uni.showLoading({
								title: '保存中',
								mask: true
							})
							if (this.isUpdate == 1) {
								await postFormAction(this.url.update, formDate);
							} else if (this.isUpdate == 0) {
								await postFormAction(this.url.create, formDate);
							}
							this.close();
						} finally {
							uni.hideLoading()
						}
					} else {
						console.log('验证失败');
					}
				});
			},
			close() {
				var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				var prevPage = pages[pages.length - 2]; //上一个页面'
				prevPage.isRefresh = true
				uni.navigateBack();
			},
			updateTitle(title) {
				// // 获取当前页面对象
				// const pages = getCurrentPages(); // 返回当前页面栈的信息
				// const currentPage = pages[pages.length - 1]; // 获取最后一个打开的页面

				// // 设置新的标题
				// currentPage.$page.meta.title = title;

				// 更新导航栏标题
				uni.setNavigationBarTitle({
					title,
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.schedule_add_or_edit {
		padding: 20upx;
		background-color: #fff;
	}
</style>